<?php
/**
 * 库存出入库记录
 * (model)
 */
namespace App\Models\Inventory;

use App\Models\Basics\SysArea;
use App\Models\Product\ProductClassify;
use App\Models\Product\ProductSku;
use App\Util\User;
use Illuminate\Database\Eloquent\Model;
class Record extends Model
{
    protected $table = 'inventory_record';

    protected $guarded = [];

    public function area(){
        return $this->belongsTo(SysArea::class,'area_id');
    }

    public function sku(){
        return $this->belongsTo(ProductSku::class,'psku_id');
    }

    /**
     * 动作类型（来源类型）
     */
    const ACTION_RECEIVE = 1; //收货
    const ACTION_MIX = 2; //组合
    const ACTION_SPLIT = 3; //拆分
    const ACTION_DELIVERY = 4; //发货
    public static $_actionType = [
        self::ACTION_RECEIVE => '收货',
        self::ACTION_MIX => '组合',
        self::ACTION_SPLIT => '拆分',
        self::ACTION_DELIVERY => '发货'
    ];

    /**
     * 出入库类型
     */
    const TYPE_IN = 1; //入库
    const TYPE_OUT = 2; //出库
    public static $_recordType = [
        self::TYPE_IN => '入库',
        self::TYPE_OUT => '出库'
    ];

    public static function getDownloadData($re){
        $user = [];
        foreach ($re as $row){
            $temp = [];
            $temp['record_no'] = $row->record_no;
            $temp['psku_code'] = $row->sku->psku_code ?? '';
            $temp['season'] = ProductClassify::$_season[$row->sku->classify->season ?? 3];
            $temp['classify'] = $row->sku->classify->title ?? '';
            $temp['area'] = $row->area->area ?? '';
            $temp['action_type'] = self::$_actionType[$row->action_type];
            $temp['record_type'] = self::$_recordType[$row->record_type];
            $temp['num'] = $row->num;
            if(!array_key_exists($row->user_id,$user)){
                $user[$row->user_id] = User::getUsernameById($row->user_id);
            }
            $temp['user_id'] = $user[$row->user_id];
            $temp['created_at'] = $row->created_at;
            $temp['psku_cn'] = $row->sku->psku_cn ?? '';
            yield $temp;
        }
    }
}
